<!DOCTYPE html>
<html>
	<head>
		<title></title>
		<meta charset="UTF-8"/>
	</head>

	<body>
		<input type="button" value="填充成绩" onclick="fill()" />
		<input type="button" value="平均分排序" onclick="fill(1)" />
		<input type="button" value="英语排序" onclick="fill(2)" />
		<input type="button" value="数学排序" onclick="fill(3)" />
		<table id="tbl" border="1">
			<tr>
				<td>学号</td>
				<td>英语</td>
				<td>数学</td>
				<td>平均成绩</td>
			</tr>
		</table>
		
		<script type="text/javascript">
			function score(studentid, english, math) {
			      this.studentid = studentid;
			      this.english = english;
			      this.math = math;
			        
			      this.average = function(){
			        return (this.english + this.math) / 2.0;
			      };
			    }
			
			    function createScores() {
			      var scores = new Array();
			      var s1 = new score(1, 89, 90);
			      var s2 = new score(2, 95, 89);
			      var s3 = new score(3, 92, 78);
			      scores.push(s1);
			      scores.push(s2);
			      scores.push(s3);
			
			      return scores;
			    }
			
			    function sortByAverage(scores) {
			      scores.sort(
			        function (s1, s2) {
			          return s2.average() - s1.average();
			        }
			      );
			    }
			
			    function sortByEnglish(scores) {
			      scores.sort(
			        function (s1, s2) {
			          return s2.english - s1.english;
			        }
			      );
			    }
			
			    function sortByMath(scores) {
			      scores.sort(
			        function (s1, s2) {
			          return s2.math - s1.math;
			        }
			      );
			    }
			
			    function fill(sortType) {
			      var tbl = document.getElementById("tbl");
			      clearTable();
			      var data = createScores();
			      switch (sortType) {
			        case 1:
			          sortByAverage(data);
			          break;
			        case 2:
			          sortByEnglish(data);
			          break;
			        case 3:
			          sortByMath(data);
			          break;
			      }

			      for (var i = 0; i < data.length; i++) {
			        tr = document.createElement("tr");
			
			        td = document.createElement("td");
			        td.innerHTML = data[i].studentid;
			        tr.appendChild(td);
			
			        td = document.createElement("td");
			        td.innerHTML = data[i].english;
			        tr.appendChild(td);
			
			        td = document.createElement("td");
			        td.innerHTML = data[i].math;
			        tr.appendChild(td);
			
			        td = document.createElement("td");
			        td.innerHTML = data[i].average();
			        tr.appendChild(td);
			
			        tbl.appendChild(tr);
			      }
			    }
			
			    function clearTable() {
			      var tbl = document.getElementById("tbl");
			      while (tbl.childElementCount > 1) {
			        tbl.removeChild(tbl.lastChild);
			      }
			    }
		</script>
	</body>

</html>